<!--
 * @Author: Li Zengkun
 * @Date: 2022-09-08 21:33:30
 * @LastEditors: Li Zengkun
 * @LastEditTime: 2022-09-09 11:15:57
 * @Description: 评分组件
-->
<template>
  <div ref="rateSlider">
    <span
      v-for="item in stars"
      :key="item"
      class="default"
      :style="{
        cursor: props.disabled
          ? 'no-drop'
          : props.readonly
          ? 'auto'
          : 'pointer',
      }"
      :class="{ active: item <= curValue }"
      @mouseenter="onMouseenter(item)"
      @mouseleave="onMouseleave()"
      @click="onClick(item)"
    >
      <slot name="character"><icon-star-fill /></slot>
    </span>
    <span>{{ defaultText[textValue] }}</span>
  </div>
</template>
 
<script setup>
import { ref, reactive, watch, computed, onMounted } from "vue";
import { Message } from "@arco-design/web-vue";

const props = defineProps({
  //默认值
  defaultValue: {
    type: Number,
    default: 0,
  },
  //星星个数
  count: {
    type: Number,
    default: 5,
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  color: {
    type: String,
    default: "#f7ba1e",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  modelValue: {
    type: Number,
  },
  texts:{
    type:Number,
    default:["😖垃圾", "🙁不满意", "😐凑合", "🙂还行", "😁牛逼"]
  }
});

const emit = defineEmits(["update:modelValue"]);

// 监听评分 value 是否越界
watch(
  () => props.modelValue,
  (newValue, oldValue) => {
    if (newValue > props.count) {
      Message.warning("已达到评分最大值!");
      emit("update:modelValue", props.count);
      return;
    }
    if (newValue < 1) {
      Message.warning("已达到评分最小值!");
      emit("update:modelValue", 1);
      return;
    }
    curValue.value = newValue;
  }
);

const curValue = ref(props.modelValue || props.defaultValue);

let preValue = 0;
const rateSlider = ref(null);
const defaultText = props.texts;

// 初始化颜色
onMounted(() => {
  rateSlider.value.style.setProperty("--rate-color", props.color);
});

const textValue = computed(() => {
  return (
    Math.ceil(curValue.value / Math.round(props.count / defaultText.length)) - 1
  );
});

const stars = ref(Array.from({ length: props.count }, (_, i) => 1 + i));

const onMouseenter = (num) => {
  if (props.readonly || props.disabled) return;
  preValue = curValue.value;
  curValue.value = num;
};
const onMouseleave = () => {
  if (props.readonly || props.disabled) return;
  curValue.value = preValue;
};

const onClick = (num) => {
  if (props.readonly || props.disabled) return;
  preValue = num;
  emit("update:modelValue", num);
};
</script>

<style lang='less' scoped>
.default {
  font-size: 25px;
  color: var(--color-neutral-3);
  padding-right: 7px;
  svg {
    transition: transform 0.1s ease-out;
  }
  &:hover {
    svg {
      transform: scale(1.2);
    }
  }
  &.active {
    color: var(--rate-color);
  }
}
</style>

